#include "robot.h"
#include "export.h"

map<uint32_t, Robot* > Robot::m_mrobots;
pthread_mutex_t Robot::m_mutex;

int32_t Robot::init()
{
	if (pthread_mutex_init(&m_mutex, NULL) != 0)
	{
		return -1;
	}

	return 0;
}

int32_t Robot::destroy()
{
	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return -1;
	}

	if (!m_mrobots.empty())
	{
		return -2;
	}

	pthread_mutex_unlock(&m_mutex);
	if (pthread_mutex_destroy(&m_mutex) != 0)
	{
		return -3;
	}

	return 0;
}

int32_t Robot::create(uint32_t id)
{
	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return -1;
	}

	if (m_mrobots.find(id) != m_mrobots.end())
	{
		pthread_mutex_unlock(&m_mutex);
		return -2;
	}

	Robot *pRobot = new Robot(id);
	if (pRobot == NULL) 
	{
		pthread_mutex_unlock(&m_mutex);
		return -3;
	}

	m_mrobots[id] = pRobot;

	pthread_mutex_unlock(&m_mutex);
	return 0;
}

int32_t Robot::remove(uint32_t id)
{
	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return -1;
	}

	if (m_mrobots.find(id) == m_mrobots.end())
	{
		pthread_mutex_unlock(&m_mutex);
		return -2;
	}

	Robot *pRobot = m_mrobots[id];
	delete pRobot;
	m_mrobots.erase(id);

	pthread_mutex_unlock(&m_mutex);
	return 0;
}

Robot *Robot::get(uint32_t id)
{
	if (pthread_mutex_lock(&m_mutex) != 0)
	{
		return NULL;
	}

	map<uint32_t, Robot* >::iterator it = m_mrobots.find(id);
	if (it != m_mrobots.end())
	{
		Robot *pRobot = it->second;
		pthread_mutex_unlock(&m_mutex);
		return pRobot;
	}

	pthread_mutex_unlock(&m_mutex);
	return NULL;
}

Robot::Robot(uint32_t id)
	: m_id(id)
{}

void Robot::loop()
{
	goSleep(2000);

	log(DEBUG, getid(), "update");
}
